package com.vineetska.contact.activity;

/**
 * @author vineet shukla
 * @email: vineetska@gmail.com
 * Nov 5, 2011
 */
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.vineetska.contact.R;
import com.vineetska.contact.adapter.ContactsListAdapter;
import com.vineetska.contact.utils.ProjectUtil;

public class Contacts extends Activity{

	private Cursor mCursor;
    private ContentResolver mContactResolver;
    @SuppressWarnings("unused")
	private String mId, mPhoneNum, mName;
    String[] mProjection;
    private ListView mListView, mSortListView;
    private TextView memptyView;
    private ContactsListAdapter adapter;
    private String mSelectedContactName;
    private String mSelectedContactNumber;
    private Vector<String> mContacts, mContactNumbers, mContactsSorted;
    private ProgressDialog mProgressDialog;
    private Handler mHandler = new Handler();

    //Update UI inside thread.
    final Runnable mUpdateResults = new Runnable() {
		public void run() {
			updateResultsInUi();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contacts);

		memptyView = (TextView)findViewById(R.id.empty_txt);
		mListView = (ListView)findViewById(R.id.cont_list);
		mSortListView = (ListView)findViewById(R.id.sort_list);

		mListView.setCacheColorHint(0);
		mSortListView.setCacheColorHint(0);
		ArrayAdapter<String> sortAadapter = new ArrayAdapter<String>(Contacts.this, R.layout.alpha_list_item, getResources().getStringArray(R.array.alphabets));
		mSortListView.setAdapter(sortAadapter);

		mContacts = new Vector<String>();

		mProjection = new String[] {
			Phone._ID,
			Phone.DISPLAY_NAME,
		};

	    mContactResolver = getContentResolver();
	    mProgressDialog = ProgressDialog.show(Contacts.this, null, "Please wait...", true, true);
	    accessPhoneBook();

	    mListView.setOnItemLongClickListener(new ListView.OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				mSelectedContactName = mListView.getItemAtPosition(arg2).toString();
				fetchContactNumber(mSelectedContactName);
				return false;
			}
		});

	    mSortListView.setOnItemClickListener(new ListView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				View v = mListView.getChildAt(0);
				int top = (v == null) ? 0 : v.getTop();
				int position = mContactsSorted.indexOf(mSortListView.getItemAtPosition(arg2).toString());
				if(position >= 0){
					mListView.setSelectionFromTop(position, top);
					mListView.setSelection(position);
				}
			}
	    });

	    registerForContextMenu(mListView);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);
		int _size = mContactNumbers.size();
		if (mContactNumbers != null && _size > 0){
			for (int i = 0; i < _size; i++) {
				menu.add(mContactNumbers.get(i));
			}
			menu.add("Delete");
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		if (item.toString().equalsIgnoreCase("delete")) {
			deleteContact(mSelectedContactName);

		}else {
			mSelectedContactNumber = item.toString();
			showDialog(0);
		}
		return super.onContextItemSelected(item);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog dialog = new AlertDialog.Builder(this).create();
		LayoutInflater inflator = LayoutInflater.from(Contacts.this);
		View view = inflator.inflate(R.layout.menu_dialog, null);
		Button _call = (Button)view.findViewById(R.id.btn_call);
		Button _sms = (Button)view.findViewById(R.id.btn_sms);

		_call.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ProjectUtil.processCallRequest(getApplicationContext(), mSelectedContactNumber);
				removeDialog(0);
			}
		});

		_sms.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v) {
				ProjectUtil.openSmsScreen(getApplicationContext(), mSelectedContactNumber);
				removeDialog(0);
			}
		});

		dialog.setView(view);

		return dialog;
	}

	/**
	 * Fetch phonebook contacts.
	 */
	private void accessPhoneBook(){
		try{
			new Thread(new Runnable(){
				public void run() {
					mCursor = mContactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null, null, null, ContactsContract.Data.DISPLAY_NAME + " ASC");
					if(mCursor.getCount() > 0){
				    	mCursor.moveToFirst();
				    	do{
				    		mId = mCursor.getString(mCursor.getColumnIndex(ContactsContract.Data.CONTACT_ID));
					    	mName = mCursor.getString(mCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
					    	if(!mContacts.contains(mName))
					    		mContacts.add(mName);
				        }while(mCursor.moveToNext());
				    }
					sortContacts(mContacts);
				}
			}).start();
		}catch(Exception e){
			mHandler.post(mUpdateResults);
		}
	}

	/**
	 * Get the contacts numbers of the specific contact name.
	 * @param contactName
	 */
	private void fetchContactNumber (String contactName) {
		mContactNumbers = new Vector<String> ();
		mCursor = mContactResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.Data.DISPLAY_NAME + "=?", new String[]{contactName}, null);
		if(mCursor.getCount() > 0) {
			mCursor.moveToFirst();
			do{
				String number = mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
				if (!mContactNumbers.contains(number)) {
					mContactNumbers.add(number);
				}
			}while(mCursor.moveToNext());
		}
	}

	/**
	 * Get the sorted contacts.
	 * @param contacts
	 */
	private void sortContacts(Vector contacts){
		mContactsSorted = new Vector<String>();
		int size = contacts.size();
		for(int i = 0; i < 26; i++){
			for(int k = 0; k < size; k++){
				if(contacts.get(k).toString().startsWith(String.valueOf(Character.toChars(65 + i)))){
					if(mContactsSorted.contains(String.valueOf(Character.toChars(65 + i)))){
						mContactsSorted.add(contacts.get(k).toString());
					}else{
						mContactsSorted.add(String.valueOf(Character.toChars(65 + i)));
						mContactsSorted.add(contacts.get(k).toString());
					}
				}
			}
		}
		mHandler.post(mUpdateResults);
	}

	private void updateResultsInUi(){
		if(mContacts != null && mContacts.size() > 0) {
			mProgressDialog.dismiss();
			adapter = new ContactsListAdapter(Contacts.this, mContactsSorted);
			mListView.setAdapter(adapter);
		}
		else{
			mProgressDialog.dismiss();
			memptyView.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * Delete contact.
	 * @param contactName
	 */
	private void deleteContact(String contactName){
		mCursor.moveToFirst();
		String _lookupKey = mCursor.getString(mCursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
		Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, _lookupKey);
		mContactResolver.delete(uri, null, null);
		mContacts.remove(contactName);
		sortContacts(mContacts);
	}

}
